//
//  PhotoViewerViewController.swift
//  01-微博项目搭建
//
//  Created by Adolph on 15/5/21.
//  Copyright (c) 2015年 Adolph. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD
class PhotoViewerViewController: UIViewController, UIScrollViewDelegate {
   /// 图像的缩放比例
    var scale: CGFloat = 1
   ///显示图像的 URl
    var imageURL: NSURL? {
        didSet {
            //下载图像显示
            SVProgressHUD.show()
            
            // 清空之前的 image
            imageView.image = nil
            
            SDWebImageManager.sharedManager().downloadImageWithURL(imageURL!, options: nil, progress: nil) { (image, error, _, _, _) -> Void in
                SVProgressHUD.dismiss()
//                println(image)
                if error != nil {
                  SVProgressHUD.showErrorWithStatus("加载图片错误")
                    return
                
                }
               self.setupImageSize(image)
            }
        }
    }
    
    ///设置图像,计算图像的大小
    private func setupImageSize(image: UIImage) {
        //重置 scroller的属性
        resetScrollView()
       println("下载完成，图像大小是 :\(image.size)")
        let size = scaleImageSize(image)
        println("缩放后的大小 \(size)")
        
        //设置图像
        imageView.image = image
        
        //设置图像视图的大小
        imageView.frame = CGRectMake(0, 0, size.width, size.height)
        
        //现在判断图片的长短图
        if size.height > view.bounds.height {
          //长图 - 置顶 - 设置滚动区域
            scrollView.contentSize = size
        } else {
         // 设置滚动视图的缩进
            let top = (view.bounds.height - size.height) * 0.5
            scrollView.contentInset = UIEdgeInsetsMake(top, 0, 0, 0)
        
        }
    
    }
    
    ///重置 scrollerView 的属性
    //防止cell重用的时候，scrollerView被拉到看不到的地方
    private func resetScrollView() {
       scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentSize = CGSizeZero
        scrollView.contentOffset = CGPointZero
    }
    ///按照屏幕的宽度计算缩放后的图像尺寸
    private func scaleImageSize(image: UIImage) -> CGSize {
      //计算比例
      let scale = image.size.width / view.bounds.size.width
       //对应比例下得h
      let h = image.size.height / scale
        return CGSizeMake(view.bounds.size.width, h)
    }
    
    ///图像视图
    lazy var imageView: UIImageView = {
       let iv = UIImageView ()
        
        // 添加手势
        let pinch = UIPinchGestureRecognizer(target: self, action: "pinch:")
        iv.addGestureRecognizer(pinch)
        
        
        // 开启imageview的用户交互能力
        iv.userInteractionEnabled = true
    
        return iv
    }()
    
    ///滚动视图
    lazy var scrollView: UIScrollView = {
        let s = UIScrollView(frame: self.view.bounds)
        //支持缩放
        //1.设置代理
        s.delegate = self
        //2. 最小和最大缩放比例
        s.minimumZoomScale = 0.5
        s.maximumZoomScale = 2.0
        return s
    }()
    
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
        // 添加滚动视图
        view.addSubview(scrollView)
        //将图像视图添加到滚动视图
        scrollView.addSubview(imageView)
    
    }
    
    //MARK: - ScrollView 的代理
    ///返回要缩放的视图
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
//    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
//        <#code#>
//    }
    ///缩放完成，释放手势后调用
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        //判断整体的缩放比例 < 1.0 说明交互式转场
        if scale < 1.0 {
           completeTransition(true)
            return
        }
        //重新调整图像的间距
        //计算顶部的间距离
        let top = (scrollView.frame.height - view.frame.height) * 0.5
        
        if top > 0 {
          scrollView.contentInset = UIEdgeInsetsMake(top, 0, 0, 0)
        } else {
          // top < 0 说明图片放大的结果，已经超出了scrollView
            scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    /**
    结论：scrollView 是通过修改 视图的 transform 来实现的缩放
    
    var a: CGFloat  缩放比例
    var b: CGFloat
    var c: CGFloat
    var d: CGFloat  缩放比例
    var tx: CGFloat x位移
    var ty: CGFloat y位移
    
    a,b,c,d一起决定了旋转
    */
    /// 只要是缩放，就会调用
    func scrollViewDidZoom(scrollView: UIScrollView) {
//        println(NSStringFromCGAffineTransform(imageView.transform))
        //根据 image
        if imageView.transform.a < 1.0 {
         scale = imageView.transform.a
            // 开始交互转场
            startInteractiveTransition(self)
        }
    }
    func pinch(gesture: UIPinchGestureRecognizer) {
      self.scale = gesture.scale
        
        //判断手势的状态
        //手势变化
        if gesture.state == UIGestureRecognizerState.Changed {
          //建立形变矩阵
            let teansform = CGAffineTransformMakeScale(scale, scale)
            // 缩小
            if scale < 1.0 {
              // 开始交互方式转场
               startInteractiveTransition(self)
            }else {
              imageView.transform = CGAffineTransformMakeScale(gesture.scale, gesture.scale)
            }
        }else if gesture.state == UIGestureRecognizerState.Ended || gesture.state == UIGestureRecognizerState.Cancelled {
           // 手势停止或者取消
            // 判断缩放比例
            if scale < 0.5 {
               completeTransition(true)
            }
        
        }
     }


}

/// 交互式转场协议
extension PhotoViewerViewController: UIViewControllerInteractiveTransitioning {
  
    //transitionContext: 是提供转场信息的
   ///开始交互转场
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        // 将目标视图控制器的视图，添加到容器视图中
        let toViewVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
        //获得目标控制器的视图
        let toView = toViewVC!.view
        
        // snapshotViewAfterScreenUpdates 能建立目标视图的快照
        let dummyView = toView.snapshotViewAfterScreenUpdates(false)
        
        // 把dummyView添加到当前View中
        transitionContext.containerView().insertSubview(dummyView, belowSubview: view)
        // 将当前视图控制器的视图 alpha 降低
        view.transform = CGAffineTransformMakeScale(scale, scale)
        view.alpha = scale
    }
}

extension PhotoViewerViewController: UIViewControllerContextTransitioning {

    ///转场的容器视图
    func containerView() -> UIView {
     return view.superview!
    }
    
    ///是否转场结束
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 取参与转场的视图控制器 － 提供转场到哪里的控制器
    func viewControllerForKey(key: String) -> UIViewController? {
        if key == UITransitionContextToViewControllerKey {
          // rootViewController －> MainTabBarController
            return UIApplication.sharedApplication().keyWindow!.rootViewController
        }else {
          return self
        }
    }
    
    // MARK: - ---可以不考虑---
    func isAnimated() -> Bool {
     return true
    }
    
    func isInteractive() -> Bool {
      return true
    }
    
    func transitionWasCancelled() -> Bool {
     return false
    }
    
    func presentationStyle() -> UIModalPresentationStyle {
        return UIModalPresentationStyle.Custom
    }
    
    func updateInteractiveTransition(percentComplete: CGFloat) { }
    
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}
    
    func viewForKey(key: String) -> UIView? {
      return nil
    }
    func targetTransform() -> CGAffineTransform {
     return CGAffineTransformIdentity
    }
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect{
      return CGRectZero
    }
    
    func finalFrameForViewController(vc: UIViewController) -> CGRect {
      return CGRectZero
    }
}